<?php

namespace app\apiadmin\service\order;

use app\apiadmin\controller\live\MyOrder;
use app\apiadmin\controller\live\UnionApp;
use app\apiadmin\controller\live\UnionAppFuWuShang;
use app\apiadmin\controller\user\User;
use app\apiadmin\model\action\ActionModel;
use app\apiadmin\model\order\OrderModel;
use app\apiadmin\model\selled_order\SelledOrderModel;
use app\apiadmin\service\data\CommStaticDictService;
use app\apiadmin\service\data\RedisService;
use app\common\utils\Res;
use DateTime;
use DateTimeZone;
use think\facade\Db;

class OrderService
{

    /**
     * @author: zwx
     * @Description: 根据条件查询数据列表
     * @param {*} $param
     * @Date: 2024-05-12 14:50:39
     */
    public static function getlist($param)
    {
        $limit = !isset($param['pageSize']) ? 10 : (int) $param['pageSize'];
        $offset = ($param['pageNumber'] - 1) * $limit;

        $map = [];
        $map["o.del"] = 0;
        // $map["u.del"] = 0;
        // $map["c.del"] = 0;

        if (isset($param["order_num"]) && !empty($param["order_num"])) {
            $map["o.order_num"] = $param["order_num"];
        }
        if (isset($param["coursename"]) && !empty($param["coursename"])) {
            $map[] = ["c.name", 'like', '%' . $param["coursename"] . '%'];
        }
        if (isset($param["from"]) && in_array($param["from"], [0, 1])) {
            $map["o.from"] = $param["from"];
        }
        if (isset($param["tel"]) && !empty($param["tel"])) {
            $map["o.tel"] = $param["tel"];
        }
        if (isset($param["state"]) && !empty($param["state"])) {
            $map["o.state"] = $param["state"];
        } else {
            if ($param["state"] === "0") {
                $map["o.state"] = $param["state"];
            }
        }
        if (isset($param["create_time"]) && !empty($param["create_time"])) {
            $map[] = ["o.create_time", '>', $param["create_time"][0]];
            $map[] = ["o.create_time", '<=', $param["create_time"][1]];
        }

        if (isset($param["pay_time"]) && !empty($param["pay_time"])) {
            $map[] = ["o.pay_time", '>', $param["pay_time"][0]];
            $map[] = ["o.pay_time", '<=', $param["pay_time"][1]];
        }
        if (isset($param["liveId"]) && !empty($param["liveId"])) {
            $map[] = ["o.liveId", 'in', $param["liveId"]];
        }
        if (isset($param["user_name"]) && !empty($param["user_name"])) {
            $map['m.user_name'] = $param["user_name"];
        }
        if (isset($param['signin_status']) && !empty($param["signin_status"])) {
            // $map['i.signin_status'] = $param["signin_status"];
        }

        $findName = "o.*,c.name as coursename,m.nick_name,m.user_name";

        $result = OrderModel::pageMap($map, $findName, $offset, $limit, $param);

        //查询接量助教
        $unionids = array_column(json_decode($result, true), "wx_unionid");
        $where = array();
        $where[] = array('a.union_id', 'in', $unionids);

        $findName = 'a.union_id,b.name,a.teacher_id';
        $result3 = ActionModel::getJieliangZhujiao($where, $findName);

        foreach ($result as $k => $v) {
            $result[$k]['pay_method'] = CommStaticDictService::FormatWithDict('pay_method', $result[$k]['pay_method']);
            $result[$k]['statename'] = CommStaticDictService::FormatWithDict('state', $result[$k]['state']);
            $result[$k]['from'] = CommStaticDictService::FormatWithDict('from', $result[$k]['from']);
            $result[$k]['fee2'] = number_format(intval($v['fee']) / 100, 2);
            $result[$k]['nick_name'] = $result[$k]['nick_name'] ? $result[$k]['nick_name'] . '->' . $result[$k]['user_name'] : '';

            $result[$k]['jieliangzhujiao'] = '-'; //接量助教
            foreach ($result3 as $k3 => $v3) {
                if ($v['wx_unionid'] == $v3['union_id']) {
                    $result[$k]['jieliangzhujiao'] = $v3['name'];
                }
            }
        }

        $total = OrderModel::pageMapCount($map, $param);

        $data = [
            'list' => $result,
            'total' => $total,
        ];
        return Res::ok($data);
    }

    public static function getMyOrder($param)
    {
        $limit = !isset($param['limit']) ? 10 : (int) $param['limit'];
        $offset = ($param['page'] - 1) * $limit;

        $map = [];
        $map["o.del"] = 0;

        if ($param["state"] != '' && $param["state"] !== 0) {
            $map["o.state"] = $param["state"];
        }
        if ($param["userid"] != '') {
            $map["o.user_id"] = $param["userid"];
        }
        $findName = "o.*,c.name as coursename,c.img";
        $result = OrderModel::getMyOrder($map, $findName, $offset, $limit);

        foreach ($result as $k => $v) {
            $result[$k]['pay_method'] = CommStaticDictService::FormatWithDict('pay_method', $result[$k]['pay_method']);
            $result[$k]['state'] = CommStaticDictService::FormatWithDict('state', $result[$k]['state']);
            $result[$k]['order_from'] = CommStaticDictService::FormatWithDict('order_from', $result[$k]['order_from']);
            $result[$k]['show'] = 0;

        }

        $total = OrderModel::pageMapCount($map);
        $data = [
            'list' => $result,
            'total' => $total,
        ];
        return Res::ok($data);
    }

    public static function getMyOrderInfo($param)
    {
        $map = [];
        $map["o.del"] = 0;

        if ($param["id"]) {

            $map["o.id"] = $param["id"];
        }
        $findName = "o.*,c.name as coursename,c.img";
        $result = OrderModel::infoMap($map, $findName);
        // var_dump($result);

        $result[0]['pay_method'] = CommStaticDictService::FormatWithDict('pay_method', $result[0]['pay_method']);
        $result[0]['state'] = CommStaticDictService::FormatWithDict('state', $result[0]['state']);
        $result[0]['order_from'] = CommStaticDictService::FormatWithDict('order_from', $result[0]['order_from']);
        $data = [
            'datas' => $result,
        ];
        return Res::ok($data);
    }

    public static function tuikuan($params)
    {

        $map = [];
        $map["o.del"] = 0;
        $map["o.id"] = $params["id"];
        $findName = "o.*";

        $order = OrderModel::pageMap($map, $findName, 0, 10)[0];

        if (!$order) {
            return Res::error('未查询到订单信息');
        }
        $order = $order->toArray();
        // 查询订单 退款数据
        $selledOrderModel = new SelledOrderModel();
        $where = [];
        $where['del'] = 0;
        $where['state'] = 1;
        $where['order_num'] = $order['order_num'];
        // 已经退款总金额
        $refund_total = $selledOrderModel->where($where)->sum('payer_refund');
        // 申请退款金额
        $customer_refund = intval($params['amount'] * 100);
        // 检查 可退款金额
        // payer_total 用户支付金额

        if ($customer_refund + $refund_total > $order['fee']) {
            return Res::error('退款金额超过用户支付金额!');
        }
        $refund_num = $selledOrderModel->where($where)->count('*');
        //        dd($refund_num);
        $refund_num++;
        if ($customer_refund == $order['fee'] && !$refund_total) {
            // 全额退款
            $part_type = 3;
        } else {
            if ($customer_refund + $refund_total == $order['fee']) {
                // 全部退款
                $part_type = 1;
            } else {
                // 部分退款
                $part_type = 2;
            }
        }
        // 退款订单 编号
        $out_request_no = 'T' . $refund_num . $order['order_num'];

        if ($order['pay_method'] == 1) { //微信退款
            if (strtotime($order['pay_time']) > strtotime('2024-08-23 23:30:16')) { //2024年8月23日23:30:16后走服务商退款，之前走直连退款
                $result = UnionAppFuWuShang::tuikuan($order['order_num'], $out_request_no, $order['fee'], $customer_refund, $order['accountid']);
            } else {
                $result = UnionApp::tuikuan($order['order_num'], $out_request_no, $order['fee'], $customer_refund);
            }
            // $result=[
            //     'code'=>200,
            //     'body'=>'{"create_time":"2024-08-16 11:15:23","refund_id":"111111111","out_refund_no":"'.$out_request_no.'","out_trade_no":"'.$order['order_num'].'","transaction_id":"99999999999","amount":{"payer_total":"11111","payer_refund":"22222"}}'
            // ];

            if ($result['code'] != 200) {
                return Res::error($result['body']);
                die;
            }
            $data = array();
            $orderdata = array();
            $orderdata['orderid'] = $order['id'];
            $orderdata['order_num'] = $order['order_num'];
            $orderdata['liveId'] = $order['liveId'];

            $body = json_decode($result['body'], true);

            $data['state'] = 3;
            $orderdata['state'] = 2;
            $orderdata['part_type'] = $part_type;

            $dateTimeString = $body['create_time'];
            // 创建DateTime对象
            $dateTime = new DateTime($dateTimeString);
            // 设置时区
            $timeZone = new DateTimeZone('Asia/Shanghai'); // 或者使用 '+08:00' 替换
            $dateTime->setTimeZone($timeZone);
            // 转换为时间戳
            $create_time = $dateTime->getTimestamp();

            $data['refund_id'] = $body['refund_id'];
            $data['refund_num'] = $body['out_refund_no'];
            $data['order_num'] = $body['out_trade_no'];
            $data['transaction_id'] = $body['transaction_id'];

            $data['create_time'] = date('Y-m-d H:i:s', $create_time);
            $data['payer_total'] = $body['amount']['payer_total'];
            $data['payer_refund'] = $body['amount']['payer_refund'];

            $data['reason'] = $params["reason"];
            $data['wx_openid'] = $order["wx_openid"];
            $data['wx_unionid'] = $order["wx_unionid"];
            $data['courseid'] = $order["courseid"];
            $data['liveId'] = $order["liveId"];

            $id = OrderModel::createSelledOrder($data);
            $data['selledid'] = $id;

            //更新订单表
            if ($refund_num == 1) {
                $orderdata['refund_time'] = date('Y-m-d H:i:s', $create_time);
            }
            $id = OrderModel::updateOrderStatus($orderdata);

            MyOrder::afterRefundOrder($order);

            return Res::ok($data);

        } else if ($order['pay_method'] == 2) { //支付宝退款
            if (strtotime($order['pay_time']) > strtotime('2024-08-23 19:00:00')) { //2024年8月23日23:30:16后走服务商退款，之前走直连退款
                $result_ali = User::alipay_refund2($order['trade_no'], $customer_refund, $order['order_num'], $out_request_no, $part_type);
            } else {
                $result_ali = User::alipay_refund($order['trade_no'], $customer_refund, $order['order_num'], $out_request_no, $part_type);
            }
            $d['remark'] = date('Y-m-d H:i:s') . '---支付宝退款--' . $order['trade_no'] . '-----' . json_encode($result_ali);
            DB::table('xh_siyu_user_remark')->save($d);
            //         $result_ali=[
            // "code"=> 0,
            // "message"=> "退款成功",
            // "result"=>'{
            // "code": "10000",
            // "msg": "Success",
            // "buyer_logon_id": "253***@qq.com",
            // "fund_change": "N",
            // "gmt_refund_pay": "2024-11-03 10:09:20",
            // "out_trade_no": "SY1730210424695116",
            // "refund_detail_item_list": [{
            //     "amount": "2999.00",
            //     "fund_channel": "ALIPAYACCOUNT"
            // }],
            // "refund_fee": "2999.00",
            // "send_back_fee": "2999.00",
            // "trade_no": "2024102922001484611418002837",
            // "buyer_open_id": "061e_66V3wspFNbwKO0JSozg69lk7DptD_7Yzl-CRT4PrY5"}'];

            if ($result_ali['code'] != 0) {
                return Res::error('退款失败');
            }

            if (strtotime($order['pay_time']) > strtotime('2024-08-23 19:00:00')) { //2024年8月23日23:30:16后走服务商退款，之前走直连退款
                $ali = json_decode($result_ali['result'], true);
            } else {
                $ali = json_decode($result_ali['result'], true)['alipay_trade_refund_response'];
            }
            $data = array();

            $orderdata = array();
            $orderdata['orderid'] = $order['id'];
            $orderdata['order_num'] = $order['order_num'];
            $orderdata['liveId'] = $order['liveId'];
            $orderdata['part_type'] = $part_type;
            $orderdata['state'] = 3; // 订单状态

            $create_time = $ali['gmt_refund_pay'];

            $data['state'] = 1; // 售后订单退款状态
            $data['refund_id'] = $ali['trade_no'];
            $data['refund_num'] = $out_request_no;
            $data['order_num'] = $order['order_num'];
            $data['create_time'] = $create_time;
            $data['payer_total'] = $order['payer_total'];
            $data['payer_refund'] = $customer_refund;
            $data['reason'] = $params["reason"];
            $data['courseid'] = $order["courseid"];
            $data['pay_time'] = $create_time;
            // dump($data);
            $id = OrderModel::createSelledOrder($data);
            $data['selledid'] = $id;
            //更新订单表
            if ($refund_num == 1) {
                $orderdata['refund_time'] = $create_time;
            }
            // dd($orderdata);
            $id = OrderModel::updateOrderStatus($orderdata);

            //给公域订单打标记
            if ($order['order_id']) {
                $where = [
                    'id' => $order['order_id'],
                ];
                $gongyuorder = Db::table('xh_order_1')->where($where)->find();
                if ($gongyuorder) {
                    $update_data = [
                        'new_tuikuan_tag' => 1,
                        'new_tuikuan_tag_time' => $create_time,
                    ];
                    Db::table('xh_order_1')->where($where)->save($update_data);
                }
            }

            MyOrder::afterRefundOrder($order);

            return Res::ok($data);
        }

    }

    // 验证订单
    public static function validate_order($userId, $liveId)
    {
        $status = 0;
        $user = DB::table('xh_siyu_user')->where('id', $userId)->find();
        $unionId = $user['unionid'] ?? null;
        $phone = $user['phone'] ?? 0;

        if (!empty($unionId) && !empty($phone)) {
            $where = 'sy_user_id=' . $userId . ' and sy_user_union_id="' . $unionId . '" and sy_user_phone=' . $phone . ' and validate_phone=' . $phone . ' and xh_order_id is not null and zhujiao is not null';
            $wheres = 'sy_user_id=' . $userId . ' and sy_user_union_id="' . $unionId . '" and (sy_user_phone=' . $phone . ' or validate_phone=' . $phone . ') and xh_order_id is not null and zhujiao is not null';
            $query = '`pay_time` is not null and ( `wx_union_id` = "' . $unionId . '" or `tel` = "' . $phone . '")';
        } elseif (!empty($unionId)) {
            $where = 'sy_user_id=' . $userId . ' and sy_user_union_id="' . $unionId . '" and xh_order_union_id="' . $unionId . '" xh_order_id is not null and zhujiao is not null';
            $wheres = 'sy_user_id=' . $userId . ' and sy_user_union_id="' . $unionId . '" and xh_order_id is not null and zhujiao is not null';
            $query = '`wx_union_id` = "' . $unionId . '" and `pay_time` is not null';
        } elseif (!empty($phone)) {
            $where = 'sy_user_id=' . $userId . ' and sy_user_phone=' . $phone . ' and validate_phone=' . $phone . ' and xh_order_id is not null and zhujiao is not null';
            $wheres = 'sy_user_id=' . $userId . ' and (sy_user_phone=' . $phone . ' or validate_phone=' . $phone . ') and xh_order_id is not null and zhujiao is not null';
            $query = '`tel` = ' . $phone . ' and `pay_time` is not null';
        } else {
            return Res::ok(['status' => $status]);
        }
        //查询本人绑定关系
        $order = DB::table('xh_siyu_user_order_zhujiao')->where($where)->order('create_time desc')->find();
        if (empty($order)) {
            //未找到本人绑定关系
            //查询他人绑定关系
            $order = DB::table('xh_siyu_user_order_zhujiao')->where($wheres)->order('create_time desc')->find();
        }
        if (empty($order)) {
            //未找到本人和他人绑定关系
            //查询本人订单
            $order = DB::table('xh_order_1')->where($query)->order('wx_union_id desc, pay_time desc')->find();
            if (!empty($order)) {
                self::validate_order_relation($user, $order, $phone);
                $order = DB::table('xh_siyu_user_order_zhujiao')->where($where)->order('create_time desc')->find();
            }
        }
        if (empty($order)) {
            $status = 5;
        } else {
            self::validate_order_log($liveId, $status, $user, $order, $phone);
            //踢掉订单其他用户
            if ($order['sy_user_phone'] != $order['validate_phone']) {
                //手机号不同 踢掉相同手机号的用户和这个手机号绑定的其他用户  2次登录他人订单
                $wheres = 'validate_phone=' . $order['validate_phone'] . ' and sy_user_phone <>' . $order['sy_user_phone'];
            } else {
                //手机号相同 踢掉手机号不用的所有用户
                $wheres = 'validate_phone=' . $order['validate_phone'] . ' and sy_user_phone <>' . $order['validate_phone'];
            }
            $kick = DB::table('xh_siyu_user_order_zhujiao')->where($wheres)->select();
            if (!empty($kick)) {
                foreach ($kick as $k => $v) {
                    $redis = RedisService::makeService();
                    $redis->publish(env("redis.prefix") . "live_info_event", json_encode([
                        "liveId" => '' . $liveId,
                        "command" => "kick_user",
                        "params" => [
                            "user_id" => '' . $v['sy_user_id'],
                        ],
                    ]));
                }
            }

        }
        return ['status' => $status, 'order' => $order];
    }

    // 验证订单关系归纳
    public static function validate_order_relation($user, $order, $phone = 0)
    {
        //$unionId = $order['wx_union_id'] ?? $user['unionid'];
        //$unionId = $order['wx_union_id'] ?? $order['xh_order_union_id'];
        $query = 'wx_unionid="' . $order['wx_union_id'] . '"';
        $xh_user = DB::table('xh_qwuser_1')->where($query)->order('id desc')->find();
        $data = [];
        $data['sy_user_id'] = $user['id'];
        $data['sy_user_union_id'] = $user['unionid'] ?? null;
        $data['sy_user_phone'] = $user['phone'] ?? null;
        $data['validate_phone'] = $phone ?? null;
        $data['validate_type'] = $phone ? 1 : 0;
        $data['xh_order_id'] = $order['id'] ?? 0;
        $data['xh_order_num'] = $order['order_num'] ?? null;
        $data['xh_order_union_id'] = $order['wx_union_id'] ?? null;
        $data['zhujiao'] = $xh_user['zhujiao'] ?? null;
        $data['create_time'] = time();
        DB::table('xh_siyu_user_order_zhujiao')->insert($data);
    }

    // 验证订单记录
    public static function validate_order_log($liveId, $status, $user, $order, $phone = 0)
    {
        $unionId = $order['wx_union_id'] ?? $order['xh_order_union_id'];
        $query = 'wx_unionid="' . $unionId . '"';
        $xh_user = DB::table('xh_qwuser_1')->where($query)->order('id desc')->find();
        $logData = [];
        $logData['live_id'] = $liveId;
        $logData['user_id'] = $user['id'];
        $logData['user_union_id'] = $user['unionid'] ?? null;
        $logData['user_phone'] = $user['phone'] ?? null;
        $logData['validate_phone'] = $phone ?? null;
        $logData['validate_type'] = $phone ? 1 : 0;
        $logData['validate_return'] = $status > 0 ? 2 : 1;
        $logData['xh_order_id'] = $order['id'] ?? $order['xh_order_id'] ?? null;
        $logData['xh_order_num'] = $order['order_num'] ?? $order['xh_order_num'] ?? null;
        $logData['xh_order_union_id'] = $order['wx_union_id'] ?? $order['xh_order_union_id'] ?? null;
        $logData['zhujiao'] = $xh_user['zhujiao'] ?? null;
        $logData['kick'] = $user['phone'] != $phone ? 1 : 0;
        $logData['create_time'] = time();
        //$logData['desc'] = '登录验证订单记录';
        DB::table('xh_siyu_user_order_zhujiao_log')->insert($logData);
    }

}
